<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/4/12 14:10
 * Remark:
 */

namespace App\Http\Middleware\Approval;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ClientConsts\ClientConsts;
use App\Consts\RequestConsts\RequestMethodConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\Approval\OldDingTalkApprovalTemplateModel;
use App\Models\Client\ClientModel;
use App\Models\Company\CompanyModel;
use App\Models\CreditProject\CreditProjectModel;
use Closure;
use Illuminate\Http\Exceptions\HttpResponseException;

class ApprovalTemplateLegitimacyMiddleware
{
    private CompanyModel $_companyModel;
    private ClientModel $_clientBasicModel;
    private CreditProjectModel $_creditProjectModel;
    private OldDingTalkApprovalTemplateModel $_oldDingTalkApprovalTemplateModel;

    public function __construct()
    {
        $this->_companyModel = new CompanyModel();
        $this->_clientBasicModel = new ClientModel();
        $this->_creditProjectModel = new CreditProjectModel();
        $this->_oldDingTalkApprovalTemplateModel = new OldDingTalkApprovalTemplateModel();
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(\Illuminate\Http\Request $request, Closure $next): mixed
    {
        $method = strtolower($request->method());
        switch ($method){
            case RequestMethodConsts::GET_METHOD:
                //
                break;
            case RequestMethodConsts::POST_METHOD:
                $currentUser = TokenFuc::getCurrentStaffInfo();
                // 校验当前公司下客户是否存在
                $this->verifyCompanyApprovalTemplateIsExists($request['company_id']??$currentUser['company_id'],$request['ding_talk_approval_template_code']);
                // 校验公司是否存在
                $this->verifyCompanyIsExists($request['company_id']);
                break;
            case RequestMethodConsts::PUT_METHOD:
                $this->verifyApprovalTemplateIsExists($request->dingTalkApprovalTempId);
                break;
            case RequestMethodConsts::PATCH_METHOD:
                $this->verifyApprovalTemplateIsExists($request->dingTalkApprovalTempId);
                break;
            default:
                break;
        }

        return $next($request);
    }

    /**
     * 校验公司名称是否存在
     * @param $companyName
     */
    private function verifyCompanyIsExists($companyId){
        $isExist = $this->_companyModel->isExistByCondition([
            'company_id' => $companyId,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if(!$isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "当前公司不存在",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,

            ));
        }
    }

    /**
     * 检测合同模板使用情况
     * @param $companyId
     * @param $templateCode
     */
    private function verifyCompanyApprovalTemplateIsExists($companyId,$templateCode){
        $isExist = $this->_oldDingTalkApprovalTemplateModel->isExistByCondition([
            'company_id' => $companyId,
            'ding_talk_approval_template_code' => $templateCode,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if($isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "当前合同模板已被使用",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }

    /**
     * @param $approvalTemplateId
     */
    private function verifyApprovalTemplateIsExists($approvalTemplateId){
        $isExist = $this->_oldDingTalkApprovalTemplateModel->isExistByCondition([
            'ding_talk_approval_template_id' => $approvalTemplateId,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if(!$isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "当前模板不存在或已删除",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }

    private function verifyCreditProjectTotalIsGrClientCreditTotal($clientId,$creditClientLimit){
        $projectTotal =  $this->_creditProjectModel->getCreditProjectTotal($clientId);
        if($creditClientLimit < $projectTotal){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "已有信用项目额度大于客户额度",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }
}